package edu.uoc.tfc.web.tags;



import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import org.apache.commons.lang.StringUtils;



public class SelectFieldTag extends TextFieldTag 
{
    private static final long serialVersionUID = 1L;

	private boolean editable = false;
	private List<SelectOptionTag> options = new ArrayList<SelectOptionTag>();


	public boolean isEditable() {
	    return editable;
    }



	public void setEditable(boolean editable) {
	    this.editable = editable;
    }



	public List<SelectOptionTag> getOptions() {
	    return options;
    }



	public void setOptions(List<SelectOptionTag> options) {
	    this.options = options;
    }



	@Override
    protected void doStartFormField(JspWriter out) throws JspException
	{
		try
		{
			write(out, "<select name=\"" + getName() + "\" id=\"" + getId() + "\" class=\"" + getClassMode() + "\">");
			write(out, "<input type=\"hidden\" value=\"" + getValue() + "\" id=\"" + getId() + "-code"+ "\">");			
		}
		catch (Exception ex)
		{
			String message = "Error generando Desplegable: " + this.getProperty();
			throw new JspException(message);
		}
	}



	@Override
    protected void doEndFormField(JspWriter out) throws JspException
    {
		try
		{
			if (readonly())
			{
				String showedValue = "";
				if (StringUtils.isBlank(getValue()))
				{
					showedValue = "&nbsp;";
				}
				else
				{
					if (getOptions().size() > 0)
					{
						for (SelectOptionTag option : getOptions())
						{
			                if (StringUtils.equals(getValue(), option.getValue()))
		               		{
			                	showedValue = getMessage(option.getLabel(), null);
			                	break;
		               		}
		                }
					}
					else
					{
						showedValue = getValue();
					}
				}
				write(out, "<span class=\"" + getClassMode() + "\">" + showedValue + "</span>");
				write(out, "<input type=\"hidden\" name=\"" + getName() + "\" id=\"" + getId() + "\" value=\"" + getValue() + "\" />");
			}
			else
			{
				write(out,"</select>");
			}
		}
		catch (Exception ex)
		{
			String message = "Error finalizando Desplegable: " + this.getProperty();
			throw new JspException(message);
		}
    }



	protected boolean readonly()
	{
		return
			isReadonly() ||
			getForm().getType() == FormType.Readonly ||
			(
				getForm().getType() != FormType.Creation &&
				isEditableOnlyOnCreation()
			);
	}



}
